package com.caval.controller;

import com.alibaba.fastjson.JSON;
import com.caval.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    @Qualifier("UserServiceImpl")
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/user/login")
    @ResponseBody
    public String login(@RequestBody Map params, HttpSession session, HttpServletResponse response){
        String username = params.get("username").toString();
        String password = params.get("password").toString();
        Cookie cookie = new Cookie("JSESSIONID",session.getId());
        cookie.setPath("/");
        response.addCookie(cookie);
        String result = JSON.toJSONString(userService.login(username, password, session));
        return result;
    }

    @PostMapping("/user/regist")
    @ResponseBody
    public String regist(@RequestBody Map params){
        String username = params.get("username").toString();
        String password = params.get("password").toString();
        String tel = params.get("tel").toString();
        String email = params.get("email").toString();
        return userService.regist(username,password,tel,email);
    }

    @RequestMapping("/user/getUser")
    @ResponseBody
    public String getUser(HttpSession session){
        return (String) session.getAttribute("username");
    }

    @RequestMapping("/user/getUserDetail")
    @ResponseBody
    public String getUserDetail(HttpSession session){
        return JSON.toJSONString(userService.getUserById(session));
    }

    @RequestMapping("/user/logout")
    @ResponseBody
    public String logout(HttpSession session){
        session.removeAttribute("username");
        session.removeAttribute("user_id");
        return "success";
    }
}
